package com.monkey.luffer.springboot.demo.basis.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author dengkaibing
 * @Description
 * @Date 2024/8/8 22:28
 **/
public class ThreadPring2 {

    public static void main(String[] args) throws InterruptedException {

        AtomicInteger time = new AtomicInteger();
        Object lock = new Object();

        new Thread(() -> {
            for (int i = 0; i <100; i++) {
                synchronized (lock) {
                    while (time.get() % 3 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("A");
                    time.getAndIncrement();
                    lock.notifyAll();
                }
            }
            System.out.println("A is end");
        }).start();

        new Thread(() -> {
            for (int i = 0; i <100; i++) {
                synchronized (lock) {
                    while (time.get() % 3 != 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("B");
                    time.getAndIncrement();
                    lock.notifyAll();


                }
            }
            System.out.println("B is end");


        }).start();

        new Thread(() -> {
            for (int i = 0; i <100; i++) {
                synchronized (lock) {
                    while (time.get() % 3 != 2) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("C");
                    time.getAndIncrement();
                    lock.notifyAll();
                }
            }
            System.out.println("C is end");


        }).start();

        TimeUnit.SECONDS.sleep(5);
    }
}
